package dao;

import java.util.List;

import javax.persistence.Query;

import model.Book;
import model.Category;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

public class BookDao extends AbstractDao<Book> {

	public static Logger log =Logger.getLogger(BookDao.class);
	
	@SuppressWarnings("unchecked")
	public List<Book> getBooks() {
		Query query = getEm().createQuery("from Book");
		List<Book> books;
		books = query.getResultList();
		return books;
	}
	
	public Book getBookById(String id) {
		Long selectId = new Long(id);
		log.info("Recherche du book à éditer ID " + id);
		Query query = getEm().createQuery("from Book where id = :id");
		query.setParameter("id", selectId);
		Book book = (Book) query.getSingleResult();
		return book;
	}
	
	@SuppressWarnings("unchecked")
	public List<Book> getBooksByCategory(Category aCategory) {
		log.info("Recherche des books de la catégorie " + aCategory.getTitle());
		Query query = getEm().createQuery("from Book b where b.category = :category");
		query.setParameter("category", aCategory);
		List<Book> books = query.getResultList();
		return books;
	}
 
	@SuppressWarnings("unchecked")
	public List<Book> getBestSellerBooks() {
		log.info("getBestSellerBooks");
		Query query = getEm().createQuery("select b from model.OrderItem o join o.book b group by o.book.id order by count(o.id) desc");
		query.setMaxResults(30);
		List<Book> books = query.getResultList();
		return books;
	}
	
	@Transactional
	public void save(Book b) {
		log.info("Insertion du book " + b.getTitle());
		em.persist(b);
		em.flush();
	}
	
	@Transactional
	public Boolean update(Book b){
		log.info("Mise à jour du livre");
		try{
			em.merge(b);
		}catch (Exception e) {
			log.error("Echec de la mise à jour du livre " + e.getMessage());
			return false;
		}
		return true;
	}

	@Transactional
	public Boolean delete(Book b) {
		log.info("Suppression du livre");
		try{
			em.remove(em.merge(b));
		}catch (Exception e) {
			log.error("Echec de la suppression du livre ");
			return false;
		}
		return true;
	}

}
